from flasgger import swag_from
from flask import g, request
from flask.views import MethodView

from app.auth.models import User
from app.extensions import json_response
from app.text.models import Text
from config.config import MAX_CONTENT_NUM
from utils.base import login_require


class Content(MethodView):
    @login_require
    @swag_from("./apidocs/create_content.yml")
    def post(self):
        """保存 content 数据"""
        body = request.json
        user_id = g.user_id
        save_data = {"user_id": user_id, "content": body.get("content")}
        res = Text.create(**save_data)

        # 更新 user 表 content_count, word_count
        user = User.get(user_id=user_id)
        user.content_count += 1
        user.word_count += len(body["content"])
        user.save()

        # 保存记录超2000条则删除相关记录
        if user.content_count > MAX_CONTENT_NUM:
            Text.delete_oldest_content(user_id)

        return json_response(data=res.to_dict())


class Contents(MethodView):
    @login_require
    @swag_from("./apidocs/get_content.yml")
    def get(self):
        user_id = g.user_id
        query = request.values
        page_size = int(query.get("page_size", 10))
        page_num = int(query.get("page_num", 1))
        if page_num < 1:
            return json_response(
                code=400, data={"msg": "page_num must bigger than zero"}
            )
        keyword = request.values.get("keyword")
        total, text_data = Text.get_all_displays(user_id, page_size, page_num, keyword)
        user = User.get(User.user_id == user_id)
        return json_response(
            data={"total": total, "result": text_data, "word_count": user.word_count}
        )


class ContentEdit(MethodView):
    @login_require
    @swag_from("./apidocs/edit_content.yml")
    def put(self, content_id):
        body = request.json
        user_id = g.user_id
        if not body:
            return json_response(code=400, data={"msg": "没有传入更新的数据"})
        Text.update_by_id(user_id, content_id, body)
        return json_response(code=200)

    @login_require
    @swag_from("./apidocs/delete_content.yml")
    def delete(self, content_id):
        user_id = g.user_id
        Text.delete_row(user_id, content_id)
        return json_response(code=200)
